#include "FileSender.h"
#include <QDataStream>
#include <QDebug>

FileSender::FileSender(QObject *parent)
    : QObject(parent),
    tcpSocket(new QTcpSocket(this)),
    file(nullptr)
{
    connect(tcpSocket, &QTcpSocket::connected, this, &FileSender::onConnected);
    connect(tcpSocket, &QTcpSocket::errorOccurred, this, &FileSender::onError);
    connect(tcpSocket, &QTcpSocket::readyRead,this, &FileSender::onReadyRead);
}

FileSender::~FileSender()
{
    if (file && file->isOpen()) {
        file->close();
    }
    delete file;
}

bool FileSender::connectToServer(const QString &host, quint16 port)
{
    tcpSocket->connectToHost(host, port);
    return tcpSocket->waitForConnected();
}

void FileSender::sendFile(FileInformation fileInformation, const QString &filePath)
{
    file = new QFile(filePath, this);
    if (!file->open(QIODevice::ReadOnly)) {
        qDebug() << filePath<<"Failed to open file for reading:" << file->errorString();
        delete file;
        file = nullptr;
        return;
    }

    QDataStream out(tcpSocket);
    out.setVersion(QDataStream::Qt_5_15);

    // 发送header标识文件信息
    out << SENDING_FILE
        << file->size()
        << fileInformation;

    qDebug() << "发送文件大小为" << file->size();
    // 发送数据
    QByteArray buffer;
    quint16 tem = 1;
    while (!file->atEnd()) {
        buffer = file->read(1024);
        // 发送信号
        emit onSendingFile(1024 * (tem ++ ) , file->size());
        tcpSocket->write(buffer);
        tcpSocket->flush();
    }

    file->close();
    qDebug() << "文件发送成功";

}


void FileSender::onConnected()
{
    qDebug() << "Connected to server.";
}

void FileSender::onError(QAbstractSocket::SocketError socketError)
{
    qDebug() << "Socket error:" << socketError;
}

void FileSender::onDisconnected()
{
    qDebug() << "从发送端断开连接";
}

void FileSender::onReadyRead(){
    QByteArray data = tcpSocket->readAll();
    QDataStream in(data);
    Header header;
    in >> header;

    switch(header)
    {
    case RECEIVE_FILE_ERROR:
        qDebug() << "文件传输失败";
        emit FileReceivedError();
        break;
    case RECEIVE_FILE_OK:
        qDebug() << "文件传输成功";
        emit FileReceivedOk();
        break;
    default:
        qDebug() << "未知回复";
        emit UnknownReply();
        break;
    }
}
